<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第14章 Pythonic与Python杂记, 湮灭星空,博客,Python,后端">
    <meta name="description" content="本章我们将大量扩展Python的优秀写法，学会如何写出优质的Pythonic风格的代码。包括：如何让字典保持有序、lmbda表达式的应用等高级Python知识

14-1 导言

七月心语：
其实有时候写代码，看着自己写的一段一段的代码把它">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>第14章 Pythonic与Python杂记 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/3.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第14章 Pythonic与Python杂记
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/python/">
                                <span class="chip bg-color">python</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%85%A5%E9%97%A8%E4%B8%8E%E8%BF%9B%E9%98%B6/" class="post-category">
                                入门与进阶
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-01-25
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-12-06
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    9 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>本章我们将大量扩展Python的优秀写法，学会如何写出优质的Pythonic风格的代码。包括：如何让字典保持有序、lmbda表达式的应用等高级Python知识</p>
<a id="more"></a>
<h3 id="14-1-导言"><a class="header-anchor" href="#14-1-导言"></a>14-1 导言</h3>
<blockquote>
<p>七月心语：</p>
<p>其实有时候写代码，看着自己写的一段一段的代码把它们累积起来，然后分门别类的将它们整理好，其实是一件挺幸福的事情。我希望大家也能找到这样的快乐幸福的感觉，这样你才能在编程的这条路上越走越远。</p>
<p>我们把写代码当作是一种谋生的手段，这个是一点错都没有的，但是我希望在这个基础上面我们可以百尺竿头更进一步，能够把它当作自己的兴趣和爱好，这样的想法会给你带来很多意想不到的惊喜。你想成为某一个技术、某一个语言甚至是更加细分的某一个领域的专家的话，那么将 coding 只当做是谋生的手段是远远不够的。我们必须有一种持之以恒的精神不断的去研究它，相反它也会给你带来一定的快乐，然后你才能有机会成为某一块的专家。</p>
</blockquote>
<h3 id="14-2-用字典映射代替switch-case语句"><a class="header-anchor" href="#14-2-用字典映射代替switch-case语句"></a>14-2 用字典映射代替switch case语句</h3>
<ul>
<li>使用字典的<code>get(key, default)</code>方法</li>
</ul>
<pre><code class="language-python">def get_sunday():
    return 'Sunday'


def get_monday():
    return 'Monday'


def get_tuesday():
    return 'Tuesday'


def get_default():
    return 'Unknown'


switcher = {
    0: get_sunday,
    1: get_monday,
    2: get_tuesday
}
day = 6
day_name = switcher.get(day, get_default)()
print(day_name)
--------------------------------------------------
Unknown
</code></pre>
<h3 id="14-3-列表推导式"><a class="header-anchor" href="#14-3-列表推导式"></a>14-3 列表推导式</h3>
<p>问题：对 [1, 2, 3, 4, 5, 6, 7, 8] 每个元素求平方返回列表。</p>
<pre><code class="language-python">a = []
for i in range(8):
    a.append(i+1)
print('a:', a)

# 使用 map 的方式
b = list(map(lambda x: x * x, a))
print('b:', b)

# 使用列表推倒式
# c = [i * i for i in a]
c = [i ** 2 for i in a]
print('c:', c)
---------------------------------------
a: [1, 2, 3, 4, 5, 6, 7, 8]
b: [1, 4, 9, 16, 25, 36, 49, 64]
c: [1, 4, 9, 16, 25, 36, 49, 64]
</code></pre>
<p>列表推导式也是可以完成 map 所完成的功能，map 在很多语言里都有，但是列表推导式确实非常具有 Python 特色，当之无愧的是 pythonic 的写法。</p>
<h4 id="某种情况"><a class="header-anchor" href="#某种情况"></a>某种情况</h4>
<p>某种情况使用列表推导式更方便：选择性的筛选。</p>
<p>延伸问题：对 [1, 2, 3, 4, 5, 6, 7, 8] 中大于等于 5 的元素求平方返回列表。</p>
<pre><code class="language-python">a = [1, 2, 3, 4, 5, 6, 7, 8]

# c = [i * i for i in a]
c = [i ** 2 for i in a if i &gt;= 5]
print('c:', c)
---------------------------------------
c: [25, 36, 49, 64]
</code></pre>
<h4 id="列表推倒式的符号"><a class="header-anchor" href="#列表推倒式的符号"></a>列表推倒式的符号</h4>
<p>列表推导式的符号可以是<code>[]</code>、<code>{}</code>、<code>()</code></p>
<p>**当符号为<code>()</code>时：返回的是生成器，一个可迭代对象。因为元组是不可变的。**所以它的行为和典型的可变序列是有区别的。</p>
<pre><code class="language-python">a = []
for i in range(8):
    a.append(i+1)
print('a:', a)
b = list(map(lambda x: x * x, a))
print('b:', b)

# c = [i * i for i in a]
c = [i ** 2 for i in a if i &gt;= 5]
print('c:', c)

# 集合可以被推导
a = set(a)
d = {i ** 2 for i in a if i &gt;= 5}
print('d:', d)

# 元组也可以被推导
a = tuple(a)
# 返回的是生成器，一个可迭代对象
e = (i ** 2 for i in a if i &gt;= 5)
print('e:', e)

# 使用 tuple 将其转化为元组
f = tuple(e)
print('f:', f)

print('再次打印 e:', e)
g = tuple(e)
print('g:', g)
------------------------------------------------
a: [1, 2, 3, 4, 5, 6, 7, 8]
b: [1, 4, 9, 16, 25, 36, 49, 64]
c: [25, 36, 49, 64]
d: {64, 25, 36, 49}
e: &lt;generator object &lt;genexpr&gt; at 0x11051b150&gt;
f: (25, 36, 49, 64)
再次打印 e: &lt;generator object &lt;genexpr&gt; at 0x11051b150&gt;
g: ()
</code></pre>
<h3 id="14-4-字典如何编写列表推导式"><a class="header-anchor" href="#14-4-字典如何编写列表推导式"></a>14-4 字典如何编写列表推导式</h3>
<pre><code class="language-python">students = {
    '小王': 18,
    '小红': 19,
    '小青': 20
}
b = {value: key for key, value in students.items()}
print(b)

c = (key for key, value in students.items())
print(c)
for x in c:
    print(x)
--------------------------------------------------------
{18: '小王', 19: '小红', 20: '小青'}
&lt;generator object &lt;genexpr&gt; at 0x10b27b258&gt;
小王
小红
小青
</code></pre>
<h3 id="14-5-none"><a class="header-anchor" href="#14-5-none"></a>14-5 None</h3>
<p><code>None</code>在 Python 里表示空。空就是空。空本身也是一个类型，也是一个对象。</p>
<ul>
<li><code>None</code> ≠ 空字符串</li>
<li><code>None</code> ≠ 空列表</li>
<li><code>None</code> ≠ 0</li>
<li><code>None</code> ≠ False</li>
</ul>
<p>这个<code>≠</code>有两层意义：</p>
<ol>
<li>类型不同</li>
<li>值不同</li>
</ol>
<pre><code class="language-python">a = ''
b = []
c = 0
d = False

# 值不同
print(None == a)
print(None == b)
print(None == c)
print(None == d)

# 类型不同
print(type(None))
print(type(a))
print(type(b))
print(type(c))
print(type(d))

print(None is a)
print(None is b)
print(None is c)
print(None is d)
-----------------------------
False
False
False
False
&lt;class 'NoneType'&gt;
&lt;class 'str'&gt;
&lt;class 'list'&gt;
&lt;class 'int'&gt;
&lt;class 'bool'&gt;
False
False
False
False
</code></pre>
<h4 id="判空操作"><a class="header-anchor" href="#判空操作"></a>判空操作</h4>
<pre><code class="language-python">def func():
    return None


a = func()
if not a:
    print(True)
else:
    print(False)

if a is None:
    print(True)
else:
    print(False)
print(id(a))
print(id(None))

b = []
if not b:
    print(True)
else:
    print(False)

if b is None:
    print(True)
else:
    print(False)
--------------------------------
True
True
4351381368
4351381368
True
False
</code></pre>
<p>判空操作时建议使用：</p>
<pre><code class="language-python">if a:
or 
if not a:
</code></pre>
<p>这样写的好处在于，当 a 为 <strong>空字符串</strong>、<strong>空列表</strong>、<strong>空集合</strong>、<strong>空元祖</strong>、<strong>False</strong>、<strong>None</strong> 的时候都会判定 a 为 False。</p>
<blockquote>
<p>空列表：表示列表里没有元素</p>
<p>空字符串：表示字符串里没有字符</p>
<p>空集合：表示集合里没有元素</p>
<p>空元组：表示元组里没有元素</p>
<p>空序列：表示序列里没有元素</p>
</blockquote>
<h4 id="none-与-false"><a class="header-anchor" href="#none-与-false"></a>None 与 False</h4>
<ul>
<li>None 表示不存在的概念，属于 Nonetype 类型</li>
<li>False 表示真假，属于 bool 类型</li>
</ul>
<h3 id="14-6-对象存在并不一定是true"><a class="header-anchor" href="#14-6-对象存在并不一定是true"></a>14-6 对象存在并不一定是True</h3>
<p>当我们在做 if 逻辑判断的时候，Python 里几乎每一个对象都跟 bool 值有着对应关系。</p>
<pre><code class="language-python">class Test1:
    pass


class Test2:
    def __len__(self):
        return 0


test1 = Test1()
if test1:
    print(True)
    print(type(test1))
else:
    print(False)
    print(type(test1))

test2 = Test2()
if test2:
    print(True)
    print(type(test2))
else:
    print(False)
    print(type(test2))
---------------------------------------
True
&lt;class '__main__.Test1'&gt;
False
&lt;class '__main__.Test2'&gt;
</code></pre>
<p>对象到底是 True 还是 False 跟对象内部的<code>__bool__</code>、<code>__len__</code>方法有关：</p>
<pre><code class="language-python">class Test:
    def __bool__(self):
        return False

    def __len__(self):
        return 0


print(bool(Test()))
------------------------------
False
</code></pre>
<h3 id="14-7-len-与-bool-内置方法"><a class="header-anchor" href="#14-7-len-与-bool-内置方法"></a>14-7 <code>__len__</code>与<code>__bool__</code>内置方法</h3>
<h4 id="len-方法"><a class="header-anchor" href="#len-方法"></a><code>__len__</code>方法</h4>
<ol>
<li>
<p>当没有<code>__bool__</code>方法，只有<code>__len__</code>方法的时候，对象的返回结果由<code>__len__</code>的返回结果决定：</p>
<ul>
<li><code>__len__</code>方法返回 0、False 时，对象的布尔值为 False</li>
<li><code>__len__</code>返回<strong>非0整型数字</strong>、True 时，对象的布尔值为 True</li>
<li><code>__len__</code>返回非数字、非 bool 类型时，会报错</li>
</ul>
</li>
<li>
<p>我们在外部使用 <code>bool</code> 方法判断对象的时候，实际上是调用了对象内置的<code>__len__</code>方法。</p>
<pre><code class="language-python">bool(Test1()）
</code></pre>
</li>
<li>
<p>除了 <code>bool</code> 方法之外还有一个方法可以触发对象内部的<code>__len__</code>方法的调用：<code>len()</code></p>
<blockquote>
<p>如果一个对象没有内置的<code>__len__</code>方法，强制的求对象的长度是会报错的。</p>
<pre><code class="language-python">class Test:
    pass


print(len(Test))
--------------------------
Traceback (most recent call last):
  File &quot;/Users/64.py&quot;, line 13, in &lt;module&gt;
    print(len(Test))
TypeError: object of type 'type' has no len()
</code></pre>
</blockquote>
</li>
</ol>
<pre><code class="language-python">class Test1:
    pass


class Test2:
    def __len__(self):
        return 0


class Test3:
    def __len__(self):
        return 8


class Test4:
    def __len__(self):
            return True


class Test5:
    def __len__(self):
            return False


print('Test1:', bool(Test1()))
print('Test2:', len(Test2()))
print('Test2:', bool(Test2()))
print('Test3:', len(Test3()))
print('Test3:', bool(Test3()))
print('Test4:', len(Test4()))
print('Test4:', bool(Test4()))
print('Test5:', len(Test5()))
print('Test5:', bool(Test5()))
-------------------------------------
Test1: True
Test2: 0
Test2: False
Test3: 8
Test3: True
Test4: 1
Test4: True
Test5: 0
Test5: False
</code></pre>
<h4 id="bool-方法"><a class="header-anchor" href="#bool-方法"></a><code>__bool__</code>方法</h4>
<p>当<code>__bool__</code>放在存在时，<code>__len__</code>方法的返回结果不再影响对象的布尔值。</p>
<ul>
<li><code>__bool__</code>方法只能返回布尔类型</li>
</ul>
<pre><code class="language-python">class Test1:
    def __bool__(self):
        return False

    def __len__(self):
        return 0


class Test2:
    def __bool__(self):
        return False

    def __len__(self):
        return 1


class Test3:
    def __bool__(self):
        return True

    def __len__(self):
        return 0


class Test4:
    def __bool__(self):
        return True

    def __len__(self):
        return 1


print('Test1:', bool(Test1))
print('Test2:', bool(Test2))
print('Test3:', bool(Test3))
print('Test4:', bool(Test4))
print('---------------------')

print('Test1:', bool(Test1()))
print('Test2:', bool(Test2()))
print('Test3:', bool(Test3()))
print('Test4:', bool(Test4()))
---------------------------------------------------------
Test1: True
Test2: True
Test3: True
Test4: True
---------------------
Test1: False
Test2: False
Test3: True
Test4: True
</code></pre>
<blockquote>
<p>小知识：</p>
<p>在 Python2 里，决定对象布尔值的方法是<code>__nonzero__</code>：</p>
<pre><code class="language-python">class Test:
    def __nonzero__(self):
        pass
    
    def __bool__(self):
        return False
    
    def __len__(self):
        return 0
</code></pre>
<p>在 Python3 里<code>__bool__</code>方法取代了<code>__nonzero__</code>方法。</p>
</blockquote>
<h3 id="14-8-iterator与generator"><a class="header-anchor" href="#14-8-iterator与generator"></a>14-8 iterator与generator</h3>
<h3 id="14-9-装饰器的副作用"><a class="header-anchor" href="#14-9-装饰器的副作用"></a>14-9 装饰器的副作用</h3>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/01/25/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-14-zhang-pythonic-yu-python-za-ji/">https://www.klause.cn/2019/01/25/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-14-zhang-pythonic-yu-python-za-ji/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/python/">
                                    <span class="chip bg-color">python</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/01/25/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-13-zhang-shi-zhan-yuan-sheng-pa-chong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/17.jpg" class="responsive-img" alt="第13章 实战：原生爬虫">
                        
                        <span class="card-title">第13章 实战：原生爬虫</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本章我们将学习如何访问网络数据、获取与解析网络数据、爬虫的基本原理解释。并带领大家实现一个用最基础语法不使用爬虫框架的原生爬虫项目。

13-1 分析抓取目的确定抓取页面
13-2 整理爬虫常规思路

爬虫前奏

明确目的
找到数据对应的网
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-01-25
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%85%A5%E9%97%A8%E4%B8%8E%E8%BF%9B%E9%98%B6/" class="post-category">
                                    入门与进阶
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2018/12/14/python3-ru-men-yu-jin-jie-shi-pin-bi-ji/di-7-zhang-bao-mo-kuai-han-shu-yu-bian-liang-zuo-yong-yu/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/13.jpg" class="responsive-img" alt="第7章 包、模块、函数与变量作用域">
                        
                        <span class="card-title">第7章 包、模块、函数与变量作用域</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本章对Python代码的组织结构核心：包、模块与函数分别作出讲解。学习完本章后你将对Python代码的组织结构有一个非常清晰的认识。重点是函数，我们除了讲解函数的基本概念外，还将讲解Python灵活的函数参数机制（默认参数、关键字参数与列表
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-12-14
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%85%A5%E9%97%A8%E4%B8%8E%E8%BF%9B%E9%98%B6/" class="post-category">
                                    入门与进阶
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/python/">
                        <span class="chip bg-color">python</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
